#include <string.h>
#include "CHashTable.h"
#include <stdio.h>

unsigned int CHashTable_ELFHash(char *str) {
    unsigned int hash = 0;
    unsigned int x = 0;

    while (*str) {
        hash = (hash << 4) + (*str++);
        if ((x = hash & 0xF0000000L) != 0) {
            hash ^= (x >> 24);
            hash &= ~x;
        }
    }
    return (hash & 0x7FFFFFFF);
}

void CHashTable_init(CHashTable *table, struct CHashNode **tablebuf, unsigned int nodeptr_number) {
    memset(tablebuf, 0, nodeptr_number * sizeof(struct CHashNode *));
    table->table = tablebuf;
    table->table_len = nodeptr_number;
}

int CHashTable_insert(CHashTable *table, CHashNode *node) {
    unsigned int hashkey;
    CHashNode *next;
    hashkey = CHashTable_ELFHash(node->str) % table->table_len;
    if (table->table[hashkey] != 0) {
        next = table->table[hashkey];
        while (next->next != 0) {
            next = next->next;
        }
        next->next = node;
    } else {
        table->table[hashkey] = node;
    }
    return 0;
}

void *CHashTable_search(CHashTable *table, char *str) {
    CHashNode *next;
    unsigned int hashkey;
    hashkey = CHashTable_ELFHash(str) % table->table_len;
    if (table->table[hashkey] != 0) {
        next = table->table[hashkey];
        while (next != 0) {
            if (0 == strcmp(str, next->str)) {
                return next;
            } else {
                next = next->next;
            }
        }
        return 0;
    } else {
        return 0;
    }
}